package com.howard.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 包括创建表，删表，建索引等SQL脚本
 *
 * @author Howard He
 *
 */
public final class SQLScriptsUtils {

	public static final String TABLES_NODE = "tables";
	// private static final String TABLE_NODE = "table";
	public static final String TABLE_NAME_NODE = "name";
	public static final String CREATE_NODE = "create";
	public static final String DROP_NODE = "drop";

	protected static final Logger logger = LoggerFactory
			.getLogger(SQLScriptsUtils.class);

	private SQLScriptsUtils() {
	}

	/**
	 * 获取table 节点
	 *
	 * @param scriptPath
	 * @return
	 */
	private static List<Element> createScriptsForElement(final String scriptPath) {
		Document document = XmlUtils.loadXML(scriptPath);
		Element tableNode = document.getRootElement().element(TABLES_NODE);
		@SuppressWarnings("unchecked")
		List<Element> tables = tableNode.elements();
		return tables;
	}

	/**
	 * 获取创建SQL table脚本
	 *
	 * @param scriptPath
	 * @return List<String>
	 *
	 */
	public static List<String> doScriptForList(final String scriptPath,
			final String elementAttr) {
		List<Element> tables = createScriptsForElement(scriptPath);
		List<String> createSqls = new ArrayList<String>();
		for (Element element : tables) {
			createSqls.add(element.elementText(elementAttr));
		}
		return createSqls;
	}

	/**
	 * 获取创建SQL table脚本
	 *
	 * @param scriptPath
	 * @return Map<String, String>
	 */
	public static Map<String, String> doScriptForMap(final String scriptPath,
			final String elementAttr) {
		List<Element> creates = createScriptsForElement(scriptPath);
		Map<String, String> createSqlMap = new HashMap<String, String>();
		for (Element element : creates) {
			createSqlMap.put(element.attributeValue(TABLE_NAME_NODE),
					element.elementText(elementAttr));
		}
		return createSqlMap;
	}

	/**
	 * 创建指定的表
	 *
	 * @param scriptPath
	 *            xml 文件
	 * @param tableName
	 *            表名
	 * @return String create sql
	 */
	public static String doScriptForTable(final String scriptPath,
			final String tableName, final String elementAttr) {
		Map<String, String> createSqlMap = doScriptForMap(scriptPath,
				elementAttr);
		return createSqlMap.get(tableName);
	}

}
